﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using QLNHK.BLL;

namespace QLNHK
{
    public partial class FrmBackupRestore : Form
    {
        string _DatabaseName, _Server, _UserId, _Password;
        string _BackupPath, _Prefix;

        public FrmBackupRestore()
        {
            InitializeComponent();
        }

        private void FrmBackupRestore_Load(object sender, EventArgs e)
        {
            //Tao mac dinh thu muc sao luu du lieu
            string folderDataBackup = "";
            //string folderDataRemote = "";

            try
            {
                Cursor = Cursors.WaitCursor;

                Global.DB_CONNECTION = Global.ReadNodeXmlDBConnectionStrings("MSSQL");

                //Set thong tin Server
                this._Server = Global.DB_CONNECTION.Server;
                //Set thong tin Database
                this._DatabaseName = Global.DB_CONNECTION.Database;
                //Set thong tin UserName
                this._UserId = Global.DB_CONNECTION.User;
                //Set thong tin Password
                this._Password = Global.DB_CONNECTION.Pass;

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                _BackupPath = config.AppSettings.Settings["BACKUP_PATH"].Value.ToString();
                _Prefix = config.AppSettings.Settings["PREFIX"].Value.ToString();

                lbServer.Text = _Server;
                lbCSDL.Text = _DatabaseName;

                Global.CreateFolderDatabaseStructure();

                if (string.IsNullOrEmpty(_BackupPath))
                    _BackupPath = Global.PATH_DRIVER_NAME + Global.PATH_FOLDER_DATABASE_BACKUP;
                //folderDataRemote = SQL.GetFolderDatabaseRemote(_Server, _DatabaseName, _UserId, _Password);

                folderDataBackup = _BackupPath;//Global.PATH_DRIVER_NAME + Global.PATH_FOLDER_DATABASE_BACKUP;

                lblBackupPath.Text = _BackupPath = folderDataBackup;

                this.loadDataToGrid();
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
            }
            finally { Cursor = Cursors.Default; }
        }

        private void loadDataToGrid()
        {
            dsBackupRestore.Clear();
            try
            {
                dsBackupRestore = DataBackup.SelectAll();

                UGMain.DataSource = dsBackupRestore;
                UGMain.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show("Thư mục chứa dữ liệu sao lưu không tồn tại, yêu cầu cấu hình lại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnSaoLuu.Enabled = false;
                btnPhucHoi.Enabled = false;
            }
        }

        private void UGMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            UGMain.DisplayLayout.Bands[0].Columns["Size"].Hidden = true;
            UGMain.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.ResizeAllColumns;
            UGMain.DisplayLayout.Override.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.RowSelect;
        }

        private void btnSaoLuu_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                string dbNameBak = string.Format("{0}_{1}", Global.DB_CONNECTION.Database, DateTime.Now.ToString("dd_MM_yyyy_[HH_mm].bak"));

                if (string.IsNullOrEmpty(_BackupPath) || string.IsNullOrEmpty(_DatabaseName))
                    MessageBox.Show("Đường dẫn hoặc tên file không được để trống");
                else
                {
                    using (System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection())
                    {
                        cnn.ConnectionString = string.Format("Server={0};Database={1};Uid={2};Pwd={3};Connect Timeout={4}", new object[] { Global.DB_CONNECTION.Server, Global.DB_CONNECTION.Database, Global.DB_CONNECTION.User, Global.DB_CONNECTION.Pass, Global.TIME_BACKUP * 60 }); //TimeoutBackup = phút * 60 giây.

                        cnn.Open();
                        string cmdText = @"
                			                                --Default backup database                                            
                                                            --Create 10-05-2012
                                                            BEGIN
                
                                                            DECLARE @filedata  AS NVARCHAR(255)
                                                            DECLARE @filename  AS NVARCHAR(255)
                                                            DECLARE @dbName AS NVARCHAR(255)
                                                           
                                                            SET @dbName = '" + Global.DB_CONNECTION.Database + @"'
                                                            SET @filename ='" + Path.Combine(_BackupPath, dbNameBak) + @"'		                                
                                                            BACKUP DATABASE @dbName
                                                            TO DISK =@filename
                                                            WITH FORMAT,INIT,MEDIANAME = 'Z_SQLServerBackups',
                                                            NAME = 'Full Backup of AdventureWorks',
                                                            SKIP,NOREWIND,NOUNLOAD,STATS = 10;
                                                            END
                                                         ";
                        System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(cmdText);
                        sqlCmd.CommandType = CommandType.Text;
                        sqlCmd.CommandTimeout = Global.TIME_BACKUP * 60;
                        sqlCmd.Connection = cnn;
                        sqlCmd.ExecuteNonQuery();
                    }
                }

                Global.SaveNodeXmlAppSettings("LAST_BACKUP", DateTime.Now.ToString("dd/MM/yyyy"));
                Global.SaveNodeXmlAppSettings("BACKUP_PATH", _BackupPath);

                DataBackup.InsertDataBackup(dbNameBak, _BackupPath, DateTime.Now, 0, string.Empty);

                MessageBox.Show("Sao lưu dữ liệu thành công.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.loadDataToGrid();
            }
            catch (Exception ex)
            {
                string st = "Lỗi khi sao lưu dữ liệu.";
                MessageBox.Show(st + " " + ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LocalLogger.Instance().WriteMessage(ex);
            }
            finally { this.Cursor = Cursors.Default; }
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (UGMain.ActiveRow.Cells["ID"].Value != DBNull.Value)
                {
                    DataBackup.DeleteDataBackup(System.Convert.ToInt32(UGMain.ActiveRow.Cells["ID"].Value));

                    loadDataToGrid();
                }
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
    }
}